﻿using System;
using System.Collections.Generic;
using UnityEngine;

namespace Framework
{
    public class ModuleManager
    {
        private static Canvas _canvas;
            
        private static Dictionary<Type, IModule> moduleDict = new Dictionary<Type, IModule>();

        private static EventDispatcher eventDispatcher;
        
        public static void Init(Canvas canvas)
        {
            _canvas = canvas;

            eventDispatcher = new EventDispatcher();
        }
        
        public static void ShowModule(string moduleName, bool setTopView = false, params object[] data)
        {
            Type type = Type.GetType(moduleName+"Module");

            if(type == null)
            {
                Log.Error("Error：类型"+moduleName+"Module 不存在！");
                return;;
            }
            if (!typeof(IModule).IsAssignableFrom(type))
            {
                Log.Error("Error：类型"+moduleName+"不是ModuleBase子类");
                return;;
            }
            
            if (moduleDict.TryGetValue(type, out IModule module))
            {
                module.Show();
                if(setTopView)
                    module.SetTopView();
                return;
            }

            module = (IModule) Activator.CreateInstance(type,moduleName, _canvas.transform, (IModuleEventDispatcher)eventDispatcher);
            module.OnShow(data);

            moduleDict.Add(type, module);
            
            if(setTopView)
                module.SetTopView();

        }

        public static void HideModule(string moduleName)
        {
            Type type = Type.GetType(moduleName + "Module");
            if (moduleDict.TryGetValue(type, out IModule module))
            {
                module.Hide();
            }
            else
            {
                Log.Error(moduleName + "Module不存在");
            }
        }

        public static void RemoveModule(string moduleName)
        {
            Type type = Type.GetType(moduleName + "Module");
            if (moduleDict.TryGetValue(type, out IModule module))
            {
                module.Destroy();
                moduleDict.Remove(type);
            }
            else
            {
                Log.Error(moduleName + "Module不存在");
            }
        }
    }
}